#!/bin/sh

set -x
set -e

ZIGDIR="$(pwd)"
CACHE_BASENAME="llvm+clang-8.0.0-freebsd-x86_64-release"
PREFIX="$HOME/$CACHE_BASENAME"
JOBS="-j$(sysctl -n hw.ncpu)"

cd $HOME
wget -nv "https://ziglang.org/builds/$CACHE_BASENAME.tar.xz"
tar xf "$CACHE_BASENAME.tar.xz"

cd $ZIGDIR
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=$PREFIX -DCMAKE_INSTALL_PREFIX=$(pwd)/release -DZIG_STATIC=ON
make $JOBS install

# TODO test everything. right now it's skipping stuff including docs
# because for some reason @cImport is failing on the CI server.
release/bin/zig build --build-file ../build.zig test-behavior -Dskip-release

if [ -f ~/.s3cfg ]; then
  mv ../LICENSE release/
  # TODO re-enable this
  #mv ../zig-cache/langref.html release/
  mv release/bin/zig release/
  rmdir release/bin

  GITBRANCH=$(basename $GITHUB_REF)
  VERSION=$(release/zig version)
  DIRNAME="zig-freebsd-x86_64-$VERSION"
  TARBALL="$DIRNAME.tar.xz"
  mv release "$DIRNAME"
  tar cfJ "$TARBALL" "$DIRNAME"

  s3cmd put -P "$TARBALL" s3://ziglang.org/builds/

  SHASUM=$(shasum -a 256 $TARBALL | cut '-d ' -f1)
  BYTESIZE=$(wc -c < $TARBALL)

  JSONFILE="freebsd-$GITBRANCH.json"
  touch $JSONFILE
  echo "{\"tarball\": \"$TARBALL\"," >>$JSONFILE
  echo "\"shasum\": \"$SHASUM\"," >>$JSONFILE
  echo "\"size\": \"$BYTESIZE\"}" >>$JSONFILE

  s3cmd put -P --add-header="Cache-Control: max-age=0, must-revalidate" "$JSONFILE" "s3://ziglang.org/builds/$JSONFILE"
  s3cmd put -P "$JSONFILE" "s3://ziglang.org/builds/freebsd-$VERSION.json"
fi
